package cn.arnold.tree.huffmantree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanTree {
    public static void main(String[] args) {
        int[] array = {13, 7, 8, 3, 29, 6, 1};
        Node huffmanTreeRoot = createHuffmanTree(array);
        System.out.println("Huffman根节点：" + huffmanTreeRoot);
        preOrder(huffmanTreeRoot);
    }

    public static Node createHuffmanTree(int[] array) {
        // 0. 为了处理方便，将array形成node，装在ArrayList中
        List<Node> listNodes = new ArrayList<Node>();
        for (Integer value : array) {
            listNodes.add(new Node(value));
        }
        // 集合只有一个元素则说明构建Huffman树的过程已完成
        while (listNodes.size() > 1) {
            // 1. 从小到大排序
            Collections.sort(listNodes);
            //System.out.println("排序后" + listNodes);
            // 2. 取出根节点权值最小的两颗二叉树
            Node leftNode = listNodes.get(0);
            Node rightNode = listNodes.get(1);
            // 3. 组成一棵新的二叉树，该新的二叉树的根节点的权值是前面两颗二叉树根节点权值的和
            Node parent = new Node(leftNode.getValue() + rightNode.getValue());
            parent.setLeft(leftNode);
            parent.setRight(rightNode);
            // 4. 将用过的节点从集合删除，并把新生的父节点加入到集合
            listNodes.remove(leftNode);
            listNodes.remove(rightNode);
            listNodes.add(parent);
        }
        // 返回Huffman树的根节点
        return listNodes.get(0);
    }

    public static void preOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("空树...");
            return;
        }
    }
}


//为了使用Collection的排序方法，实现Compare接口
class Node implements Comparable<Node> {
    private int value;  //节点权值
    private Node left;
    private Node right;

    public Node(int value) {
        this.value = value;
    }

    // 从小到大排序
    public int compareTo(Node o) {
        return this.value - o.value;
    }

    // 前序遍历
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }


}